const express = require('express')
const fs = require('fs')
const path = require('path')
const multer = require('multer')

// const upload = multer({ dest: 'imgs/' })
const storage = multer.diskStorage({
  destination: 'imgs/',
  filename(req, file, cb) {
    // console.log(file.originalname)
    cb(null, file.originalname)
  }
})
const upload = multer({ storage })

const app = express()
app.use(express.json())

const booksPath = path.join(__dirname, 'data/books.json')

app.get('/api/books', (req, res) => {
  fs.readFile(booksPath, (err, data) => {
    if (err) return res.status(500).send({
      message: '服务器内部错误!请联系管理员!',
      data: []
    })

    const books = JSON.parse(data.toString())
    res.send({
      message: '查询图书列表成功!',
      data: books
    })
  })
})

app.post('/api/books', (req, res) => {
  console.log(req.body)
  const { bookname, author, publisher } = req.body
  if (!bookname) return res.send({ message: 'bookname 是必填项!'})
  if (!author) return res.send({ message: 'author 是必填项!'})
  if (!publisher) return res.send({ message: 'publisher 是必填项!'})

  fs.readFile(booksPath, (err, data) => {
    if (err) return res.status(500).send({
      message: '服务器内部错误!请联系管理员!',
      data: []
    })

    const books = JSON.parse(data.toString())
    const result = {
      id: books[books.length - 1] ? books[books.length - 1].id + 1 : 1,
      ...req.body,
      createdAt: new Date(),
      updateAt: new Date()
    }
    books.push(result)

    fs.writeFile(booksPath, JSON.stringify(books), err => {
      if (err) return res.status(500).send({
        message: '服务器内部错误!请联系管理员!',
        data: []
      })
      
      res.send({
        message: '添加图书成功',
        data: result
      })
    })
  })
})

app.delete('/api/books/:id', (req, res) => {
  // console.log('删除图书:', req.params.id)
  fs.readFile(booksPath, (err, data) => {
    const books = JSON.parse(data.toString())
    const index = books.findIndex(item => item.id === +req.params.id)
    // console.log(index)
    if (index === -1) return res.status(400).send({
      message: '您要删除的图书不存在'
    })
    books.splice(index, 1)
    // console.log(books)

    fs.writeFile(booksPath, JSON.stringify(books), err => {
      if (err) return res.status(500).send({
        message: '服务器内部错误!请联系管理员!',
        data: []
      })

      res.send()
    })
  })
})

app.post('/uploadimg', upload.single('avatar'), (req, res) => {
  res.send({
    message: '上传成功!'
  })
})

app.listen(3000, () => {
  console.log('服务器已启动 - http://localhost:3000')
})